package com.it.xyx.code.asyncDemo;

import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CompletableFuture;
@Service
@RequiredArgsConstructor
public class BatchInsertService {

    @Resource
    private UserDataMapper userDataMapper;

    // 每批次处理量（根据数据库配置调整）
    private static final int BATCH_SIZE = 2000;

    @Async("batchInsertExecutor")
    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public CompletableFuture<Integer> asyncBatchInsert(List<UserData> dataList) {
        return CompletableFuture.completedFuture(
                executeBatchInsert(dataList)
        );
    }

    private int executeBatchInsert(List<UserData> dataList) {
            if (dataList == null || dataList.isEmpty()) {
                return 0;
            }
            // 使用自定义SQL批量插入
            userDataMapper.batchInsert(dataList);

        return dataList.size();
    }

    public static <T> List<List<T>> partition(List<T> list, int batchSize) {
        List<List<T>> partitions = new ArrayList<>();
        for (int i = 0; i < list.size(); i += batchSize) {
            int end = Math.min(i + batchSize, list.size());
            partitions.add(list.subList(i, end));
        }
        return partitions;
    }
}
